/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ANBInterface.java
 *
 * Created on Nov 6, 2011, 10:20:20 PM
 */
package anbserver;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author An
 */
public class ANBServerMain extends javax.swing.JFrame {

    /** Creates new form ANBInterface */
    public ANBServerMain() {
        initComponents();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlCreate = new javax.swing.JPanel();
        lbName = new javax.swing.JLabel();
        lbPin = new javax.swing.JLabel();
        lbBalance = new javax.swing.JLabel();
        btnCreate = new javax.swing.JButton();
        txtName = new javax.swing.JTextField();
        txtPin = new javax.swing.JTextField();
        txtBalance = new javax.swing.JTextField();
        pnlUpdate = new javax.swing.JPanel();
        lbUName = new javax.swing.JLabel();
        lbQuantity = new javax.swing.JLabel();
        txtUName = new javax.swing.JTextField();
        txtQuantity = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnuServer = new javax.swing.JMenu();
        mniStart = new javax.swing.JMenuItem();
        mniStop = new javax.swing.JMenuItem();
        mnuManager = new javax.swing.JMenu();
        mniUI = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server");
        setResizable(false);

        pnlCreate.setBorder(javax.swing.BorderFactory.createTitledBorder("Create account"));

        lbName.setText("Name");

        lbPin.setText("Pin");

        lbBalance.setText("Balance");

        btnCreate.setText("Create");
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        txtName.setColumns(8);

        txtPin.setColumns(8);

        txtBalance.setColumns(8);

        javax.swing.GroupLayout pnlCreateLayout = new javax.swing.GroupLayout(pnlCreate);
        pnlCreate.setLayout(pnlCreateLayout);
        pnlCreateLayout.setHorizontalGroup(
            pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCreateLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlCreateLayout.createSequentialGroup()
                        .addComponent(lbBalance)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlCreateLayout.createSequentialGroup()
                        .addComponent(lbName)
                        .addGap(27, 27, 27)
                        .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlCreateLayout.createSequentialGroup()
                        .addComponent(lbPin)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtPin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(29, 29, 29)
                .addComponent(btnCreate)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        pnlCreateLayout.setVerticalGroup(
            pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlCreateLayout.createSequentialGroup()
                .addGroup(pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbName)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbPin)
                    .addComponent(txtPin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlCreateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbBalance)
                    .addComponent(txtBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCreate))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        getContentPane().add(pnlCreate, java.awt.BorderLayout.PAGE_START);

        pnlUpdate.setBorder(javax.swing.BorderFactory.createTitledBorder("Add credit"));
        pnlUpdate.setName("Server"); // NOI18N

        lbUName.setText("Name");

        lbQuantity.setText("Quantity");

        txtUName.setColumns(8);

        txtQuantity.setColumns(8);
        txtQuantity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtQuantityActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlUpdateLayout = new javax.swing.GroupLayout(pnlUpdate);
        pnlUpdate.setLayout(pnlUpdateLayout);
        pnlUpdateLayout.setHorizontalGroup(
            pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlUpdateLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlUpdateLayout.createSequentialGroup()
                        .addComponent(lbUName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtUName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlUpdateLayout.createSequentialGroup()
                        .addComponent(lbQuantity)
                        .addGap(18, 18, 18)
                        .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pnlUpdateLayout.setVerticalGroup(
            pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlUpdateLayout.createSequentialGroup()
                .addGroup(pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlUpdateLayout.createSequentialGroup()
                        .addGroup(pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lbUName)
                            .addComponent(txtUName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(pnlUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbQuantity)))
                    .addGroup(pnlUpdateLayout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(btnAdd)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(pnlUpdate, java.awt.BorderLayout.CENTER);

        mnuServer.setText("Server");

        mniStart.setText("Start");
        mniStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniStartActionPerformed(evt);
            }
        });
        mnuServer.add(mniStart);

        mniStop.setText("Stop");
        mniStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniStopActionPerformed(evt);
            }
        });
        mnuServer.add(mniStop);

        jMenuBar1.add(mnuServer);

        mnuManager.setText("Manager");

        mniUI.setText("User Info");
        mniUI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniUIActionPerformed(evt);
            }
        });
        mnuManager.add(mniUI);

        jMenuBar1.add(mnuManager);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
//kiem tra hop le
    if (txtName.getText() == null || "".equals(txtName.getText())) {
        JOptionPane.showMessageDialog(rootPane, "Account's not available !");
        return;
    }
    if ("".equals(txtPin.getText())) {
        JOptionPane.showMessageDialog(rootPane, "Pin is null !");
        return;
    }
    if ("".equals(txtBalance.getText())) {
        JOptionPane.showMessageDialog(rootPane, "Balance is null !");
        return;
    }
    //them tai khoan moi
    try {
        cdb = new ConnectDB();
        con = cdb.getConnection();
        st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        //check account exist
        boolean exist = false;
        String check = "SELECT accName FROM account";
        rs = st.executeQuery(check);
        while (rs.next()) {
            if (rs.getString("accName").equalsIgnoreCase(txtName.getText())) {
                exist = true;
            }
        }
        if (!exist) {
            String query = "INSERT INTO account(accName,pin,balance)"
                    + " VALUES('" + txtName.getText() + "','" + convertMD5(txtPin.getText()) + "'," + txtBalance.getText() + ")";
            st.executeUpdate(query);
            JOptionPane.showMessageDialog(rootPane, "Create account successful");
        } else {
            JOptionPane.showMessageDialog(rootPane, "Account is existed");
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(rootPane, "Create account false");
        ex.printStackTrace();
    } finally {
        try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(ANBServerMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}//GEN-LAST:event_btnCreateActionPerformed

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
    if (txtUName.getText() == null || "".equals(txtUName.getText())) {
        JOptionPane.showMessageDialog(rootPane, "Account's not available !");
        return;
    }
    if ("".equals(txtQuantity.getText()) || Float.parseFloat(txtQuantity.getText()) < 0) {
        JOptionPane.showMessageDialog(rootPane, "Balance's not available !");
        return;
    }

    try {
        cdb = new ConnectDB();
        con = cdb.getConnection();
        st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String query = "UPDATE  account"
                + " SET balance = balance +" + Float.parseFloat(txtQuantity.getText())
                + "WHERE accName='" + txtUName.getText() + "'";
        st.executeUpdate(query);
        con.close();
        JOptionPane.showMessageDialog(rootPane,
                "Add credit successful");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(rootPane,
                "Add credit false");
        ex.printStackTrace();
    }


}//GEN-LAST:event_btnAddActionPerformed

private void txtQuantityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtQuantityActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtQuantityActionPerformed

private void mniStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniStartActionPerformed
    try {


        //thread to use RMI
        new Thread(new Runnable() {

            @Override
            public void run() {
                int port = 12345;
                try {
                    ANBankImpl anb = new ANBankImpl();

                    Registry reg = LocateRegistry.createRegistry(port);
                    reg.rebind("connect", anb);
                    //                    reg.rebind("logIn", anb);
                    //                    reg.rebind("changePin", anb);
                    //                    reg.rebind("transfer",anb);
                    //     System.out.println("Server is running ......");
                    JOptionPane.showMessageDialog(rootPane, "Server is running ...");
                } catch (RemoteException ex) {
                    System.out.println("Ket noi voi may chu that bai.");
                }
            }
        }).start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}//GEN-LAST:event_mniStartActionPerformed

private void mniStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniStopActionPerformed
    System.exit(1);
}//GEN-LAST:event_mniStopActionPerformed

private void mniUIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniUIActionPerformed
    new UserInfo().setVisible(true);
}//GEN-LAST:event_mniUIActionPerformed
    public static String convertMD5(String input) {
        StringBuilder buf = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] output = md.digest();
            md.update(input.getBytes());
            output = md.digest();
            char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

            for (int j = 0; j < output.length; j++) {
                buf.append(hexDigit[(output[j] >> 4) & 0x0f]);
                buf.append(hexDigit[output[j] & 0x0f]);
            }

        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return buf.toString();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;




                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ANBServerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ANBServerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ANBServerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ANBServerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ANBServerMain().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCreate;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JLabel lbBalance;
    private javax.swing.JLabel lbName;
    private javax.swing.JLabel lbPin;
    private javax.swing.JLabel lbQuantity;
    private javax.swing.JLabel lbUName;
    private javax.swing.JMenuItem mniStart;
    private javax.swing.JMenuItem mniStop;
    private javax.swing.JMenuItem mniUI;
    private javax.swing.JMenu mnuManager;
    private javax.swing.JMenu mnuServer;
    private javax.swing.JPanel pnlCreate;
    private javax.swing.JPanel pnlUpdate;
    private javax.swing.JTextField txtBalance;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtPin;
    private javax.swing.JTextField txtQuantity;
    private javax.swing.JTextField txtUName;
    // End of variables declaration//GEN-END:variables
    private ConnectDB cdb = null;
    private Connection con;
    private Statement st;
    private ResultSet rs;
}
